package com.module.imageloader.loaders

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.drawable.Drawable
import android.os.Handler
import android.os.Looper
import android.view.View
import com.bumptech.glide.Glide
import com.bumptech.glide.RequestBuilder
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.target.CustomViewTarget
import com.bumptech.glide.request.target.Target.SIZE_ORIGINAL
import com.module.imageloader.cache.DiskCacheKey
import com.module.imageloader.option.ImageOptions

/**
 * date        ：2020/7/14
 * author      ：蒙景博
 * description ：
 */
@SuppressLint("CheckResult")
class GlideLoader : ImageDelegate {

    override fun loadImage(option: ImageOptions): RequestBuilder<Drawable>? {
        if (option.context == null) return null
        val builder = Glide.with(option.context).load(option.model)
        // 设置占位符
        if (option.placeHolderResId > 0 && option.placeHolderDrawable == null) {
            builder.placeholder(option.placeHolderResId)
        } else {
            builder.placeholder(option.placeHolderDrawable)
        }
        // 设置加载失败占位符
        if (option.errorHolderResId > 0 && option.errorHolderDrawable == null) {
            builder.error(option.errorHolderResId)
        } else {
            builder.error(option.errorHolderDrawable)
        }
        // 设置备用回调符
        if (option.fallbackHolderResId > 0 && option.fallbackHolderDrawable == null) {
            builder.fallback(option.fallbackHolderResId)
        } else {
            builder.fallback(option.fallbackHolderDrawable)
        }
        // 设置缩略倍数
        if (option.thumbnail > 0.0f) {
            builder.sizeMultiplier(option.thumbnail)
        }
        // 设置图片质量
        if (option.quality > 0) {
            builder.encodeQuality(option.quality)
        }
        // 设置解码格式
        builder.format(option.decodeFormat)
        // 设置编码格式
        builder.encodeFormat(option.compressFormat)
        // 取消动画
        builder.dontAnimate()
        // 是否启用预加载
        if (option.preload) {
            builder.preload()
        }
        // 设置图片大小
        if (option.size != null && (option.size.width > 0 && option.size.height > 0)) {
            builder.override(option.size.width, option.size.height)
        } else {
            builder.override(SIZE_ORIGINAL, SIZE_ORIGINAL)
        }
        // 设置加载优先级
        builder.priority(option.priority)
        // 是否仅从缓存加载数据
        builder.onlyRetrieveFromCache(option.justFromCacheLoad)
        // 设置是否跳过内存缓存
        builder.skipMemoryCache(option.skipMemoryCache)
        // 设置是否磁盘缓存模式
        builder.diskCacheStrategy(option.diskCacheStrategy)
        // 设置内存和磁盘缓存key，使调用者可以更好地控制缓存数据何时失效, 如果Key为空，则使用图片地址做key。
        if (option.diskCacheStrategy != DiskCacheStrategy.NONE) {
            if (!option.diskCacheKey.isNullOrEmpty()) {
                builder.signature(DiskCacheKey(option.diskCacheKey))
            } else {
                if (option.model != null) {
                    builder.signature(DiskCacheKey(option.model.toString()))
                }
            }
        }
        return builder
    }

    override fun <V : View> request(option: ImageOptions, callback: CustomViewTarget<V, Drawable>) {
        loadImage(option)?.into(callback)
    }

    override fun pauseRequests(context: Context) {
        Glide.with(context).pauseRequests()
    }

    override fun pauseAllRequests(context: Context) {
        Glide.with(context).pauseAllRequests()
    }

    override fun resumeRequests(context: Context) {
        Handler(Looper.getMainLooper()).post { Glide.with(context).resumeRequests() }
    }

    override fun clearDiskCache(context: Context) {
        Glide.get(context).clearDiskCache()
    }

    override fun clear(view: View) {
        Glide.with(view).clear(view)
    }

    override fun clearMemory(context: Context) {
        Glide.get(context).clearMemory()
    }

    override fun trimMemory(context: Context, level: Int) {
        Glide.get(context).trimMemory(level)
    }
}
